<?php
	/**
	* Add a product into current shopping cart
	* 
	* Cart Object Structure
	*   Product ID
	*   Product Seo Name
	*   Product Image path
	*   Price
	*   Quantity
	*   Product_state
	* 
	* @author trungdt
	* @since Oct 19, 2011
	* 
	* Change logs
	* 
	*/

	if (!defined('EXPONENT')) exit('');
	if (!defined("ABProductsModule_Carts"))
		define("ABProductsModule_Carts","ABShopCart_SessionKey");

	// how many quantity will we add?
	$quantity=1;
	if (isset($_POST['ql']))
		$quantity=intval($_POST['ql']);
	
	if (isset($_POST['id'])){
		$product_id = intval($_POST['id']);

		// get all current carts
		$carts=array();
		if (exponent_sessions_isset(ABProductsModule_Carts))
			$carts=exponent_sessions_get(ABProductsModule_Carts);

		// this product is currently in customer shopping cart? update quantity
		$cart_exist=false;
		foreach ($carts as $k=>$v){
			if ($v->id == $product_id)
			{
				$v->quantity+=$quantity;
				$cart_exist=true;
				break;
			}
		}

		if (!$cart_exist)
		{
			// product exist validator
			$product=$db->selectObject("productsmodule_products", "(public_state = 1) AND (id = {$product_id})");
			if ($product)
			{
				// get module config
				$config=$db->selectObject("productsmodule_config", "location_data = '{$product->location_data}'");
				$max=0; $min=0;
				$product = productsmodule::__ProductProcess($product, $config, $max, $min, false);
				$product=$product[0];

				$product->src = unserialize($product->location_data)->src;
				$product->quantity = $quantity;
				
				// remove html of this product for saving memory
				$product->description="";
				$product->spec="";
				$product->search_description="";
				$product->search_spec="";
				
				// add new into carts
				$carts[]=$product;
			}
		}

		// update session carts
		exponent_sessions_set(ABProductsModule_Carts, $carts);

	}

	if (exponent_javascript_inAjaxAction())
	{
		// refresh the cart
		// temporary dont need to refresh the cart
		//include(BASE."modules/productsmodule/actions/cart_on_top.php");
	}
	else
	{
		// include the action show shopping cart page
		$params=array();
		$params['module']="productsmodule";
		$params['action']='cart_view';
		$link=exponent_core_makeLink($params);
		header("Location: {$link}");
	}	
?>
